package com.lagou.util;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.util.internal.ObjectUtil;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author HuanyuZhou
 * @date 2020/6/8 10:42
 */
public class RpcDecoder extends MessageToMessageDecoder<ByteBuf> {


    private Class<?> clazz;

    private Serializer serializer;

    private final Charset charset;

    public RpcDecoder(Class<?> clazz, Serializer serializer) {
        this.clazz = clazz;
        this.serializer = serializer;
        this.charset = Charset.defaultCharset();
    }



    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        byte[] bytes = new byte[msg.readableBytes()-4];
        System.out.println("服务器收到的字节长度:"+msg.readableBytes());
        int i = msg.readerIndex();
        i = i+4;
        msg.getBytes(i,bytes);
        //从ByteBuf中读取出客户端传过来的字节、并交给JsonSerializer去解码
        Object deserialize = serializer.deserialize(clazz, bytes);
        //解码后添加到List中，交给下一个handler去处理（这里是UserServiceHandler）
        out.add(deserialize);
    }

}
